/*
 * SPDX-FileCopyrightText: 2010-2021 Espressif Systems (Shanghai) CO LTD
 *
 * SPDX-License-Identifier: Apache-2.0
 */

#ifndef _ESP_CPU_H
#define _ESP_CPU_H

#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>

#include "hal/cpu_hal.h"

#ifdef __cplusplus
extern "C" {
#endif

#define ESP_WATCHPOINT_LOAD 0x40000000
#define ESP_WATCHPOINT_STORE 0x80000000
#define ESP_WATCHPOINT_ACCESS 0xC0000000

typedef uint32_t esp_cpu_ccount_t;

/** @brief Read current stack pointer address
 *
 */
static inline void *esp_cpu_get_sp(void)
{
    return cpu_hal_get_sp();
}

/**
 * @brief Stall CPU using RTC controller
 * @param cpu_id ID of the CPU to stall (0 = PRO, 1 = APP)
 */
void esp_cpu_stall(int cpu_id);

/**
 * @brief Un-stall CPU using RTC controller
 * @param cpu_id ID of the CPU to un-stall (0 = PRO, 1 = APP)
 */
void esp_cpu_unstall(int cpu_id);

/**
 * @brief Reset CPU using RTC controller
 * @param cpu_id ID of the CPU to reset (0 = PRO, 1 = APP)
 */
void esp_cpu_reset(int cpu_id);

/**
 * @brief Returns true if a JTAG debugger is attached to CPU
 * OCD (on chip debug) port.
 *
 * @note If "Make exception and panic handlers JTAG/OCD aware"
 * is disabled, this function always returns false.
 */
bool esp_cpu_in_ocd_debug_mode(void);

static inline esp_cpu_ccount_t esp_cpu_get_ccount(void)
{
    return cpu_hal_get_cycle_count();
}

static inline void esp_cpu_set_ccount(esp_cpu_ccount_t val)
{
    cpu_hal_set_cycle_count(val);
}

/**
 * @brief Set and enable a hardware watchpoint on the current CPU
 *
 * Set and enable a hardware watchpoint on the current CPU, specifying the
 * memory range and trigger operation. Watchpoints will break/panic the CPU when
 * the CPU accesses (according to the trigger type) on a certain memory range.
 *
 * @note Overwrites previously set watchpoint with same watchpoint number.
 *       On RISC-V chips, this API uses method0(Exact matching) and method1(NAPOT matching) according to the
 *       riscv-debug-spec-0.13 specification for address matching.
 *       If the watch region size is 1byte, it uses exact matching (method 0).
 *       If the watch region size is larger than 1byte, it uses NAPOT matching (method 1). This mode requires
 *       the watching region start address to be aligned to the watching region size.
 *
 * @param no    Hardware watchpoint number [0..SOC_CPU_WATCHPOINTS_NUM - 1]
 * @param adr   Watchpoint's base address, must be naturally aligned to the size of the region
 * @param size  Size of the region to watch. Must be one of 2^n and in the range of [1 ... SOC_CPU_WATCHPOINT_SIZE]
 * @param flags One of ESP_WATCHPOINT_* flags
 * @return ESP_ERR_INVALID_ARG on invalid arg, ESP_OK otherwise
 */
esp_err_t esp_cpu_set_watchpoint(int no, void *adr, int size, int flags);

/**
 * @brief Clear a watchpoint
 *
 * @param no Watchpoint to clear
 *
 */
void esp_cpu_clear_watchpoint(int no);

#ifdef __cplusplus
}
#endif

#endif // _ESP_CPU_H
